<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 按钮 -->
      <el-button type="primary" @click="openAdd">添加用户</el-button>
      <!-- 表格区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 下拉框 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row type="flex" align="middle" v-for="(item,index) in scope.row.children" :key="item.id" :class="['bottombd',index === 0 ? 'topbd' : '']">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag class="expand-col" closable @close="removeRightById(scope.row,item.id)">
                  {{item.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二、三级权限 -->
              <el-col :span="19">
                <el-row type="flex" align="middle" v-for="(item2,index2) in item.children" :key="item2.id" :class="[index2 === 0 ? '' : 'topbd']">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" class="expand-col" closable @close="removeRightById(scope.row,item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" class="expand-col" v-for="item3 in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEdit(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加/删除角色弹出框 -->
    <el-dialog :title="isEdit ? '编辑角色':'添加角色'" :visible.sync="dialogVisible" width="50%" @close="dialogClose">
      <!-- 主体内容区域 -->
      <el-form :model="rolesForm" ref="formRoles" label-width="100px" :rules="roleRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isEdit ? editRoles() : addRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="rightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree ref="rightTree" :data="rightList" :props="defaultProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="roleRightIdList"></el-tree>
      <span slot="footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import $http from '@/utils/resquest.js'
export default {
  data() {
    return {
      // 弹框开关
      dialogVisible: false,
      // 角色列表
      rolesList: [],
      // 权限列表
      rightList: [],
      // 角色信息
      rolesForm: {},
      // 验证规则
      roleRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      // 是否是编辑
      isEdit: false,
      // 分配权限弹框
      rightDialogVisible: false,
      // 指定树形控件的节点
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      // 要勾选的节点的id
      roleRightIdList: [],
      // 角色id
      roleId: ''
    }
  },
  methods: {
    // 分配权限
    // 渲染弹出框数据
    async showSetRightDialog(role) {
      this.roleId = role.id
      this.rightDialogVisible = true
      // 初始化数组
      this.roleRightIdList = []
      const { data: res } = await $http.get('rights/tree')
      // console.log(res.data)
      this.rightList = res.data
      this.getRoleRightList(role, this.roleRightIdList)
    },
    // 获取角色对应的id
    getRoleRightList(role, list) {
      // 如果是三级权限，就转存id到数组中
      if (!role.children) return list.push(role.id)
      // 如果不是三级权限，就再次调用
      role.children.forEach(value => {
        this.getRoleRightList(value, list)
      })
    },
    // 确认分配权限
    async allotRight() {
      // 获取所有被选中和版选中的节点的id,即 key
      const keys = [...this.$refs.rightTree.getCheckedKeys(), ...this.$refs.rightTree.getHalfCheckedKeys()]
      // 把数组转成字符传
      const rids = keys.join(',')
      const { data: res } = await $http.post(`roles/${this.roleId}/rights`, { rids })
      if (res.meta.status !== 200) return this.$message.error('权限分配失败')
      this.$message.success('权限分配成功')
      this.rightDialogVisible = false
      this.getRolesList()
      // console.log(rids)
    },
    // 点击小叉叉删除对应的权限
    removeRightById(role, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // console.log('删除')
          const { data: res } = await $http.delete(`roles/${role.id}/rights/${rightId}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          // console.log(res)
          // this.getRolesList()
          // 数据驱动视图
          role.children = res.data
          // console.log('删除' + role.id, rightId)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          // console.log(role, rightId)
        })
    },

    // 编辑角色
    async openEdit(id) {
      this.isEdit = true
      this.dialogVisible = true
      // 请求数据
      const { data: res } = await $http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      // 转存、渲染数据
      // console.log(res)
      this.rolesForm = res.data
    },
    editRoles() {
      this.$refs.formRoles.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('请填写完整！')
        const { data: res } = await $http.put(`roles/${this.rolesForm.roleId}`, {
          roleName: this.rolesForm.roleName,
          roleDesc: this.rolesForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('数据获取失败')
        this.getRolesList()
        this.dialogVisible = false
      })
    },
    // 添加角色
    openAdd() {
      // 关闭修改面板
      this.isEdit = false
      this.dialogVisible = true
    },
    addRole() {
      this.$refs.formRoles.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('请填写完整！')
        const { data: res } = await $http.post('roles', this.rolesForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.getRolesList()
        this.dialogVisible = false
      })
    },
    // 获取角色数据
    async getRolesList() {
      const { data: res } = await $http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      this.rolesList = res.data
    },
    // 弹窗关闭
    dialogClose() {
      this.$refs.formRoles.resetFields()
    },
    // 删除角色
    deleteRoles(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await $http.delete(`roles/${id}`)
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>
<style lang="less" scoped>
.topbd {
  border-top: 1px solid #eee;
}
.expand-col {
  margin: 7px;
}
.bottombd {
  border-bottom: 1px solid #eee;
}
</style>